package com.sunnada.edu.timer.service;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.util.Utils;
import com.sunnada.edu.timer.bean.TimeSet;
/**
 * explain  考勤
 * @author  WJQ 2016-08-13
 * version 1.0
 */

public class StatisticsCrdThread implements Runnable{
    private static final Logger logger = LoggerFactory.getLogger(StatisticsCrdThread.class);
	private String personType;//0：教师，1：学生
	private List<HashMap<String, String>> mlist;    
	private String todayData;
	private String schoolId;
	private String weekDay;
	private boolean isMakeUp;
	PubDao dao;
	public StatisticsCrdThread() {
	
	} 
	public StatisticsCrdThread(List<HashMap<String, String>> mlist,String todayData,String weekDay,String personType, boolean isMakeUp , String schoolId) {
		this.mlist = mlist;
		this.personType = personType;
		this.todayData = todayData;
		this.weekDay = weekDay;
		this.isMakeUp = isMakeUp;
		this.schoolId = schoolId;
		this.dao = AppContext.getInstance().getPubDao();
	}
	@Override
	public void run() {
		statistics();
	}
	private void statistics() {
		for(HashMap<String, String> mmap:mlist){
			String CARD_ID = mmap.get("CARD_ID");
			String P_ID = mmap.get("P_ID");
			TimeSet timeSet = getTimeSet(P_ID,CARD_ID,schoolId);
			if(Utils.isNull(timeSet)){
				continue;
			}else{
				String amOnSate = getTimeCrd(P_ID,CARD_ID,timeSet.getAmOnTime(),timeSet.getAmOnLastTime(),timeSet.getAmOnTime_(),"on");
				String amOffSate = getTimeCrd(P_ID,CARD_ID,timeSet.getAmOffTime(),timeSet.getAmOffLastTime(),timeSet.getAmOffTime_(),"off");
				String pmOnSate = getTimeCrd(P_ID,CARD_ID,timeSet.getPmOnTime(),timeSet.getPmOnLastTime(),timeSet.getPmOnTime_(),"on");
				String pmOffSate = getTimeCrd(P_ID,CARD_ID,timeSet.getPmOffTime(),timeSet.getPmOffLastTime(),timeSet.getPmOffTime_(),"off");
				String atOnSate = getTimeCrd(P_ID,CARD_ID,timeSet.getAtOnTime(),timeSet.getAtOnLastTime(),timeSet.getAtOnTime_(),"on");
				String atOffSate = getTimeCrd(P_ID,CARD_ID,timeSet.getAtOffTime(),timeSet.getAtOffLastTime(),timeSet.getAtOffTime_(),"off");
				System.out.println(CARD_ID);
				System.out.println(amOnSate);
				System.out.println(amOffSate);
				System.out.println(pmOnSate);
				System.out.println(pmOffSate);
				System.out.println(atOnSate);
				System.out.println(atOffSate);
				amOnSate = excludeLeave(P_ID,CARD_ID,"amOn",amOnSate);
				amOffSate = excludeLeave(P_ID,CARD_ID,"amOff",amOffSate);
				pmOnSate = excludeLeave(P_ID,CARD_ID,"pmOn",pmOnSate);
				pmOffSate = excludeLeave(P_ID,CARD_ID,"pmOff",pmOffSate);
				atOnSate = excludeLeave(P_ID,CARD_ID,"atOn",atOnSate);
				atOffSate = excludeLeave(P_ID,CARD_ID,"atOff",atOffSate);
				System.out.println(amOnSate);
				System.out.println(amOffSate);
				System.out.println(pmOnSate);
				System.out.println(pmOffSate);
				System.out.println(atOnSate);
				System.out.println(atOffSate);
				String dSql = "delete from T_CRD_STATISTICS where CARD_ID='"+CARD_ID+"' and PERSON_ID='"+P_ID+"' and CRD_DATE = '"+todayData+"' and STATE not in ('31','32','33','34')";
				dao.delete(dSql);
				if(!("00".equals(amOnSate))){
					String addSql = "Insert into T_CRD_STATISTICS(PERSON_TYPE,PERSON_ID,CARD_ID,CRD_DATE,TIME_TYPE,STATE,REC_TIME)values('"+personType+"','"+P_ID+"','"+CARD_ID+"','"+todayData+"','amOn','"+amOnSate+"',SYSDATE)";
					dao.insert(addSql);
				}
				if(!("00".equals(amOffSate))){
					String addSql = "Insert into T_CRD_STATISTICS(PERSON_TYPE,PERSON_ID,CARD_ID,CRD_DATE,TIME_TYPE,STATE,REC_TIME)values('"+personType+"','"+P_ID+"','"+CARD_ID+"','"+todayData+"','amOff','"+amOffSate+"',SYSDATE)";
					dao.insert(addSql);
				}
				if(!("00".equals(pmOnSate))){
					String addSql = "Insert into T_CRD_STATISTICS(PERSON_TYPE,PERSON_ID,CARD_ID,CRD_DATE,TIME_TYPE,STATE,REC_TIME)values('"+personType+"','"+P_ID+"','"+CARD_ID+"','"+todayData+"','pmOn','"+pmOnSate+"',SYSDATE)";
					dao.insert(addSql);
				}
				if(!("00".equals(pmOffSate))){
					String addSql = "Insert into T_CRD_STATISTICS(PERSON_TYPE,PERSON_ID,CARD_ID,CRD_DATE,TIME_TYPE,STATE,REC_TIME)values('"+personType+"','"+P_ID+"','"+CARD_ID+"','"+todayData+"','pmOff','"+pmOffSate+"',SYSDATE)";
					dao.insert(addSql);
				}
				if(!("00".equals(atOnSate))){
					String addSql = "Insert into T_CRD_STATISTICS(PERSON_TYPE,PERSON_ID,CARD_ID,CRD_DATE,TIME_TYPE,STATE,REC_TIME)values('"+personType+"','"+P_ID+"','"+CARD_ID+"','"+todayData+"','atOn','"+atOnSate+"',SYSDATE)";
					dao.insert(addSql);
				}
				if(!("00".equals(atOffSate))){
					String addSql = "Insert into T_CRD_STATISTICS(PERSON_TYPE,PERSON_ID,CARD_ID,CRD_DATE,TIME_TYPE,STATE,REC_TIME)values('"+personType+"','"+P_ID+"','"+CARD_ID+"','"+todayData+"','atOff','"+atOffSate+"',SYSDATE)";
					dao.insert(addSql);
				}
			}
		}
	}
	
	
	private TimeSet getTimeSet(String P_ID,String Id,String schoolId){
		StringBuilder sql = new StringBuilder();
		if("1".equals(personType)){
			sql.append("select t.* from T_STUDENT_SET t,t_groupstudent g,T_STUDENT te ");
			sql.append("where t.GROUP_ID = g.GROUP_ID ");
			sql.append("and g.STUDENT_ID = te.STUDENT_ID ");
			sql.append("and t.rec_status<>'2' ");
			sql.append("and to_date(t.startdata,'yyyy-MM-dd') < to_date('"+todayData+"','yyyy-MM-dd') ");
			sql.append("and to_date(t.enddata,'yyyy-MM-dd') > to_date('"+todayData+"','yyyy-MM-dd') ");
			sql.append("and te.card_id='"+Id+"' ");
			sql.append("and te.student_id='"+P_ID+"' ");
			sql.append("and t.school_id='"+schoolId+"' ");
			if(!isMakeUp){
			sql.append("and t.PERIOD like '%"+weekDay+"%'");
			}
		}else{
			sql.append("select t.* from T_STAFF_SET t,t_groupstaff g,t_teacher te ");
			sql.append("where t.GROUP_ID = g.GROUP_ID ");
			sql.append("and g.TEACHER_ID = te.TEACHER_ID ");
			sql.append("and t.rec_status<>'2' ");
			sql.append("and to_date(t.startdata,'yyyy-MM-dd') < to_date('"+todayData+"','yyyy-MM-dd') ");
			sql.append("and to_date(t.enddata,'yyyy-MM-dd') > to_date('"+todayData+"','yyyy-MM-dd') ");
			sql.append("and te.card_id='"+Id+"' ");
			sql.append("and te.teacher_id='"+P_ID+"' ");
			sql.append("and t.school_id='"+schoolId+"' ");
			if(!isMakeUp){
			sql.append("and t.PERIOD like '%"+weekDay+"%'");
			}
		}
		List<HashMap<String, String>>  l =   (List<HashMap<String, String>>) dao.selectList(sql.toString());
		if(l.size()>0){
//			HashMap<String, String> smap=(HashMap<String, String>) l.get(0);
			TimeSet s = new TimeSet();
			for(HashMap<String, String> smap:l){
				String amon=smap.get("AM_ONTIME");
				String amoff=smap.get("AM_OFFTIME");
				String pmon=smap.get("PM_ONTIME");
				String pmoff=smap.get("PM_OFFTIME");
				String aton=smap.get("AT_ONTIME");
				String atoff=smap.get("AT_OFFTIME");
				if(Utils.isNotNull(amon)){
					String a1=amon.substring(0,amon.indexOf("-"));
					String a2=amon.substring(amon.indexOf("-")+1,amon.length());
					s.setAmOnTime(a1);
					s.setAmOnTime_(a2);
					s.setAmOnLastTime(smap.get("AM_ONLASTTIME"));
				}
				if(Utils.isNotNull(amoff)){
					String a1=amoff.substring(0,amoff.indexOf("-"));
					String a2=amoff.substring(amoff.indexOf("-")+1,amoff.length());
					s.setAmOffTime(a1);
					s.setAmOffTime_(a2);
					s.setAmOffLastTime(smap.get("AM_OFFLASTTIME"));
				}
				if(Utils.isNotNull(pmon)){
					String a1=pmon.substring(0,pmon.indexOf("-"));
					String a2=pmon.substring(pmon.indexOf("-")+1,pmon.length());
					s.setPmOnTime(a1);
					s.setPmOnTime_(a2);
					s.setPmOnLastTime(smap.get("PM_ONLASTTIME"));
				}
				if(Utils.isNotNull(pmoff)){
					String a1=pmoff.substring(0,pmoff.indexOf("-"));
					String a2=pmoff.substring(pmoff.indexOf("-")+1,pmoff.length());
					s.setPmOffTime(a1);
					s.setPmOffTime_(a2);
					s.setPmOffLastTime(smap.get("PM_OFFLASTTIME"));
				}
				if(Utils.isNotNull(aton)){
					String a1=aton.substring(0,aton.indexOf("-"));
					String a2=aton.substring(aton.indexOf("-")+1,aton.length());
					s.setAtOnTime(a1);
					s.setAtOnTime_(a2);
					s.setAtOnLastTime(smap.get("AT_ONLASTTIME"));
				}
				if(Utils.isNotNull(atoff)){
					String a1=atoff.substring(0,atoff.indexOf("-"));
					String a2=atoff.substring(atoff.indexOf("-")+1,atoff.length());
					s.setAtOffTime(a1);
					s.setAtOffTime_(a2);
					s.setAtOffLastTime(smap.get("AT_OFFLASTTIME"));
				}
//				s.setAmOnLastTime(smap.get("AM_ONLASTTIME"));
//				s.setAmOffLastTime(smap.get("AM_OFFLASTTIME"));
//				s.setPmOnLastTime(smap.get("PM_ONLASTTIME"));
//				s.setPmOffLastTime(smap.get("PM_OFFLASTTIME"));
//				s.setAtOnLastTime(smap.get("AT_ONLASTTIME"));
//				s.setAtOffLastTime(smap.get("AT_OFFLASTTIME"));
			}
			return s;
		}else{
			return null;
		}
		
	}
	private String getTimeCrd(String P_ID,String Id,String startTime,String halfTime,String endTime,String onType){
		String crdState="";//0：正常，1：迟到，2：早退，3：未打卡，31：旷课，32：病假，33：事假，34：其他
		if(Utils.isNull(startTime)||Utils.isNull(halfTime)||Utils.isNull(endTime)){
			crdState = "00";
		}else{
			StringBuilder sql = new StringBuilder();
			sql.append("select t.* from T_CRD_DATA t ");
			sql.append("WHERE t.CARD_ID='"+Id+"' ");
			sql.append("AND t.person_id='"+P_ID+"' ");
			sql.append("AND t.REC_TIME>=to_char(to_date('"+todayData+" "+startTime+"','yyyy-mm-dd hh24:mi:ss'),'yyyymmddhh24miss') ");
			sql.append("AND t.REC_TIME<=to_char(to_date('"+todayData+" "+endTime+"','yyyy-mm-dd hh24:mi:ss'),'yyyymmddhh24miss') ");
			if("on".equals(onType)){
				sql.append("order by t.rec_time asc");
			}else{
				sql.append("order by t.rec_time desc");
			}
			List<?>  l =   dao.selectList(sql.toString());
			if(l.size()>0){
				HashMap<String, String> crdmap=(HashMap<String, String>) l.get(0);
				String crdTime = crdmap.get("REC_TIME");
				DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				    Date d1 = null;
				    Date d2 = null ;
					try {
						d1 = df.parse(crdTime);
						d2 = df1.parse(todayData+" "+halfTime);
					} catch (ParseException e) {
						// TODO 自动生成的 catch 块
						e.printStackTrace();
					}
				    long diff = d1.getTime() - d2.getTime();
				    if("on".equals(onType)){
					    if(diff<0){
					    	crdState = "0";//正常
					    }else{
					    	crdState = "1";//迟到
					    }
				    }else{
				    	if(diff<0){
					    	crdState = "2";//早退
					    }else{
					    	crdState = "0";//正常
					    }
				    }
				
			}else{
				crdState = "3";//未打卡
			}
			
		}
		return crdState;
	}
	private String excludeLeave(String P_ID,String Id,String timeType,String crdState) {
		//0：正常，1：迟到，2：早退，3：未打卡，31：旷课，32：病假，33：事假，34：其他
		StringBuilder sql = new StringBuilder();
		sql.append("select t.* from T_CRD_STATISTICS t where t.STATE like '3_' and t.CRD_DATE ='");
		sql.append(todayData);
		sql.append("' and t.card_id='");
		sql.append(Id);
		sql.append("' and t.person_id='");
		sql.append(P_ID);
		sql.append("' and t.TIME_TYPE='");
		sql.append(timeType);
		sql.append("'");
//		if("amOn".equals(timeType)){
//			sql.append("amOn");
//			sql.append("'");
//		}else if("amOff".equals(timeType)){
//			sql.append("amOff");
//			sql.append("'");
//		}else if("pmOn".equals(timeType)){
//			sql.append("pmOn");
//			sql.append("'");
//		}else if("pmOff".equals(timeType)){
//			sql.append("pmOff");
//			sql.append("'");
//		}else if("atOn".equals(timeType)){
//			sql.append("atOn");
//			sql.append("'");
//		}else if("atOff".equals(timeType)){
//			sql.append("atOff");
//			sql.append("'");
//		}
		StringBuilder dsql = new StringBuilder();
		dsql.append("delete from T_CRD_STATISTICS where CARD_ID='");
		dsql.append(Id);
		dsql.append("' and t.person_id='");
		dsql.append(P_ID);
		dsql.append("' and STATE not in ('32','33') ");
		dsql.append(" and TIME_TYPE='");
		dsql.append(timeType);
		dsql.append("'");
		List<?> l =   dao.selectList(sql.toString());
		if(l.size()>0){
			crdState ="00";
			dao.delete(dsql.toString());
		}
		return crdState;
	}
}
